package com.gem.shop.web;


import com.gem.shop.entity.Commodity;
import com.gem.shop.entity.OrderDetails;
import com.gem.shop.service.CommodityService;
import com.gem.shop.util.BeanFactory;
import com.gem.shop.util.PageBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zhang
 * @date 2020/9/17 15:47
 */
@WebServlet("/permission/commodity/*")
public class CommodityServlet extends HttpServlet{
    CommodityService commodityService = (CommodityService) BeanFactory.getBean("commodityService");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();

        //显示所有
        if ("/allType".equals(pathInfo)){
            String pageNowStr = req.getParameter("pageNow");
            List<String> allType = commodityService.findAllType();
            int pageNow;
            if (pageNowStr == null){
                pageNow = 1;
            }else {
                pageNow = Integer.parseInt(pageNowStr);
            }
            PageBean pageBean = commodityService.findCommoditysByPagesAndType(pageNow,5,"每日特价");
            req.setAttribute("allType",allType);
            req.setAttribute("pageBean",pageBean);
            req.getRequestDispatcher("/WEB-INF/pages/home.jsp").forward(req,resp);
        }

        if ("/byType".equals(pathInfo)){
            String type = req.getParameter("type");
            String name = req.getParameter("name");
            List<Commodity> commodities = commodityService.findCommoditiesByNameAndType(name, type);
            req.setAttribute("commodities",commodities);
            req.setAttribute("type",type);
            req.setAttribute("name",name);
            req.getRequestDispatcher("/WEB-INF/pages/showCommodities.jsp").forward(req,resp);
        }

        if ("/toCommodityDetail".equals(pathInfo)){
            String idStr = req.getParameter("id");
            int id = Integer.parseInt(idStr);
            Commodity commodity = commodityService.findCommodityById(id);
            req.setAttribute("commodity",commodity);
            req.getRequestDispatcher("/WEB-INF/pages/commoditiesDetails.jsp").forward(req,resp);
        }

        // 添加购物车
        if ("/addCart".equals(pathInfo)){
            String commodityId = req.getParameter("commodity_id");
            String numStr = req.getParameter("num");
            int num = Integer.parseInt(numStr);

            Commodity commodity = commodityService.findCommodityById(Integer.parseInt(commodityId));


            //购物车映射成订单明细
            OrderDetails cart = new OrderDetails(null,num,num * commodity.getPrice(),commodity.getPrice(),null,commodity);

            //检查session是否有购物车信息
            HttpSession session = req.getSession(true);
            List<OrderDetails> list = (List<OrderDetails>) session.getAttribute("cart");


            if (list == null || list.size() == 0){
                //session中没有
                list = new ArrayList<>();
            }

            boolean falg = true;
            //判单集合中是否存在该商品信息
            for (OrderDetails orderDetails : list) {
                if (orderDetails.getCommodity().getId().equals(cart.getCommodity().getId())){
                    //表示集合中已经有该商品  数量相加就可以了
                    orderDetails.setNum(orderDetails.getNum()+cart.getNum());
                    orderDetails.setSubtotal(orderDetails.getPrice() * orderDetails.getNum());
                    falg = false;
                    break;
                }
            }

            if (falg){
                //表示不满足循环中的if条件，将cart添加到集合
                list.add(cart);
            }


            session.setAttribute("cart",list);

            PrintWriter writer = resp.getWriter();
            writer.print("1");
        }

        //跳转到购物车页面
        if ("/toMyCart".equals(pathInfo)){
            req.getRequestDispatcher("/WEB-INF/pages/myCart.jsp").forward(req,resp);
        }

        //删除购物车
        if ("/deleteCart".equals(pathInfo)){
            String idStr = req.getParameter("id");
            int id = Integer.parseInt(idStr);

            HttpSession session = req.getSession();
            List<OrderDetails> cart = (List<OrderDetails>) session.getAttribute("cart");
            Iterator<OrderDetails> iterator = cart.iterator();
            while (iterator.hasNext()){
                //判断是不是要删除的购物车
                if (id == iterator.next().getCommodity().getId()){
                    iterator.remove();
                }
            }

            session.setAttribute("cart",cart);

            // TODO: 2020/10/3 重定向
            req.getRequestDispatcher("/WEB-INF/pages/myCart.jsp").forward(req,resp);
        }


        //跳转到购买商品页面
        if ("/toBuy".equals(pathInfo)){
            String idStr = req.getParameter("id");
            String numStr = req.getParameter("num");
            int id = Integer.parseInt(idStr);
            int num = Integer.parseInt(numStr);

            Commodity commodity = commodityService.findCommodityById(id);
            req.setAttribute("commodity",commodity);
            req.setAttribute("num",num);
            req.setAttribute("subtotal",num * commodity.getPrice());
            req.getRequestDispatcher("/WEB-INF/pages/payOrder.jsp").forward(req,resp);
        }
        
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
